package com.bs.blogspace.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.bs.blogspace.model.Result;
import com.bs.blogspace.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component//交给IOC容器管理
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override//目标资源方法执行前执行，返回true：放行， 返回false：不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Result<Object> err = new Result<>();
        //1.获取url
        String url = request.getRequestURI();
        log.info("登录操作，放行:{}",url);
        //2.判断请求的url中是否包涵login，是就放行
        if (url.contains("login")){
            log.info("登录操作，放行。。。。");
            return true;
        }
        //3.获取请求头中的令牌（token）
        String jwt = request.getHeader("Authorization");
        //4.判断令牌是否存在
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头为空，返回登录信息");
            err.setMessage("NOT_LOGIN");
            String notlogin = JSONObject.toJSONString(err);
            response.getWriter().write(notlogin);
            return false;
        }
        //5.解析JWT零牌
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回登录信息");
            err.setMessage("NOT_LOGIN");
            String notlogin = JSONObject.toJSONString(err);
            response.getWriter().write(notlogin);
            return false;
        }
        //6.放行
        log.info("令牌合法，放行");
        return true;
    }

    @Override//目标资源方法执行后执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override//视图渲染完毕后执行，最后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
